﻿using EndpointManagement;
using IM.Easy.Core.Filters;
using IM.Easy.Core.Utils;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;

namespace IM.Easy.Api.Filters
{
    public class EndpointAuthorizationFilter : GlobalAuthorizeFilter
    {
        public override async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            var endpoint = context.HttpContext.GetEndpoint();
            if (endpoint is RouteEndpoint routeEndpoint)
            {
                var routePattern = routeEndpoint.RoutePattern.RawText;
                var httpMethod = context.HttpContext.Request.Method;
                var api = EndPointManager.Get($"{routePattern}:{httpMethod}");
                var allowAnonymous = !api?.AuthRequired ?? true;

                if (!allowAnonymous)
                {
                    var result = await context.HttpContext.AuthenticateAsync();
                    if (!result.Succeeded)
                    {
                        ExceptionUtils.ThrowUnauthorized();
                    }
                }

            }
        }
    }
}
